package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.dao.StudentRepository;
import cn.edu.ctbu.dp01.entity.Student;
import cn.edu.ctbu.dp01.exception.RException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentService {
    private static final Logger log = LoggerFactory.getLogger(StudentService.class);

    @Autowired
    private StudentRepository studentRepository;

    public List<Student> getAll() {
        return studentRepository.findAll();
    }

    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }

    public Page<Student> getAll(Example<Student> example, Pageable pageable){
        return studentRepository.findAll(example,pageable);
    }

    public Student findById(int id) {
        return studentRepository.findById(id).orElse(null);
    }

    public Student add(Student student) {
        return studentRepository.save(student);
    }

    public Student update(Student student) {
        return studentRepository.save(student);
    }

    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public Student validateUsernameAndPassword(String sno, String password) throws Exception {
        List<Student> students = studentRepository.findBySno(sno);
        log.info("Query result for sno {}: {}", sno, students);

        if (students.size() > 0) {
            Student student = students.get(0);
            if (student.getPassword().equals(password)) {
                log.info("Validation successful for sno {}", sno);
                return student;
            } else {
                log.error("Password validation failed for sno {}", sno);
                throw new RException(REnum.LOGIN_ERR);
            }
        } else {
            log.error("No student found for sno {}", sno);
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}